package ${packageName}.mvp.model.api.interceptor;

import android.text.TextUtils;

import ${packageName}.app.AppPreference;
import com.jpxx.base.util.EncryptUtils;

import java.io.IOException;
import java.util.UUID;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.HttpUrl;

/**
 * 在请求header里加上登录获得的token
 */
public class AuthTokenInterceptor implements Interceptor {
    private static final int CODE_REDIRECT_START = 300;
    private static final int CODE_REDIRECT_END = 307;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();

        Response originalResponse = chain.proceed(generateNewRequest(originalRequest, null));

        //展示重定向如何操作
        if (originalResponse.code() >= CODE_REDIRECT_START
                && originalResponse.code() <= CODE_REDIRECT_END) {
            String redirectLocation = originalResponse.header("Location");
            if (originalResponse.body() != null) {
                originalResponse.body().close();
            }

            if (redirectLocation != null) {
                HttpUrl redirectUrl = HttpUrl.parse(redirectLocation);
                if (redirectUrl != null) {
                    return chain.proceed(generateNewRequest(originalRequest, redirectUrl));
                }
            }
        }

        return originalResponse;
    }

    private Request generateNewRequest(Request originalRequest, HttpUrl redirectUrl){
        Request.Builder newBuilder = originalRequest.newBuilder();

        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = getUUID();
        String path = originalRequest.url().encodedPath().replace("/api/","");
        String sign = EncryptUtils.encryptMD5ToString("secret=" + "jpxx-ztc" + "&timestamp=" + timestamp + "&nonce" + nonce + "&path=" + path);


        if(redirectUrl != null){
            newBuilder.url(redirectUrl);
        }

        newBuilder.header("clientId", "chargeV2")
                .header("timestamp", timestamp)
                .header("nonce", nonce)
                .header("sign", sign)
                .header("Connection", "Close");

        if(!TextUtils.isEmpty(AppPreference.getAppToken())){
            newBuilder.header("token", AppPreference.getAppToken());
        }

        return newBuilder.build();
    }

    private static String getUUID(){
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24) ;
    }
}
